package com.web.cloud.service.pub;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.cloud.constances.DBConsts;
import com.web.cloud.exception.BusinessException;
import com.web.cloud.model.pub.IOrgBaseModel;
import com.web.cloud.utils.IdGenerator;
import com.web.cloud.utils.OrgInfoHolder;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by liuhaiming on 2016-05-29.
 */
public class OrgBaseService<T extends IOrgBaseModel> extends BaseService<T> {
    public OrgBaseService() {
    }

    public String getOrgId() {
        return OrgInfoHolder.getOrgId();
    }

    protected T createVOInstance(T original) throws Exception {
        IOrgBaseModel t = (IOrgBaseModel)super.createVOInstance(original);
        t.setOrgId(this.getOrgId());
        return (T) t;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int save(List<T> arr) throws BusinessException {
        long ts = (new Date()).getTime();
        Iterator result = arr.iterator();

        while(result.hasNext()) {
            IOrgBaseModel e = (IOrgBaseModel)result.next();
            e.setId(IdGenerator.getInstance().nextId(this.getModuleCode()));
            e.setDr(DBConsts.DR_NORMAL);
            e.setOrgId(this.getOrgId());
            e.setTs(Long.valueOf(ts));
        }

        try {
            int result1 = this.dao.insertList(arr);
            return result1;
        } catch (Exception var6) {
            throw new BusinessException(var6);
        }
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int save(T entity) throws BusinessException {
        entity.setOrgId(this.getOrgId());
        return super.save(entity);
    }

    public List<T> selectAll() throws Exception {
        IOrgBaseModel t = (IOrgBaseModel)this.getGenericType().newInstance();
        t.setDr(DBConsts.DR_NORMAL);
        t.setOrgId(this.getOrgId());
        return this.dao.select((T) t);
    }

    public PageInfo<T> selectPage(int pageNum, int pageSize, String orderBy) throws Exception {
        return this.selectPage(pageNum, pageSize, orderBy, this.createVOInstance((T)null));
    }

    public PageInfo<T> selectPage(int pageNum, int pageSize, String orderBy, T t) throws Exception {
        PageHelper.startPage(pageNum, pageSize, orderBy);
        t.setDr(DBConsts.DR_NORMAL);
        t.setOrgId(this.getOrgId());
        return new PageInfo(this.dao.select(t));
    }
}
